package com.jiamao.goplay.ui.main;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.gyf.immersionbar.ImmersionBar;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.utils.HMSBIInitializer;
import com.itsnows.upgrade.OnDownloadListener;
import com.itsnows.upgrade.OnUpgradeListener;
import com.itsnows.upgrade.UpgradeClient;
import com.itsnows.upgrade.UpgradeConstant;
import com.itsnows.upgrade.UpgradeException;
import com.itsnows.upgrade.UpgradeManager;
import com.itsnows.upgrade.UpgradeUtil;
import com.itsnows.upgrade.model.bean.Upgrade;
import com.itsnows.upgrade.model.bean.UpgradeOptions;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMActivity;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.databinding.MainLayoutBinding;
import com.jiamao.goplay.ui.discover.DiscoverHomeFragment;
import com.jiamao.goplay.ui.msg.MsgHomeFragment;
import com.jiamao.goplay.ui.photo.PhotoUploadFragment;
import com.jiamao.goplay.ui.user.MeFragment;
import com.jiamao.goplay.ui.user.UserInvitationFragment;
import com.jiamao.goplay.ui.user.UserPairFragment;
import com.jiamao.goplay.util.GlideUtils;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.ui.drop.DropManager;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.mixpush.HWPushMessageService;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.tamsiree.rxkit.RxImageTool;
import com.tamsiree.rxkit.view.RxToast;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.config.ISListConfig;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.item.NormalItemView;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;
import skin.support.content.res.SkinCompatResources;
import skin.support.widget.SkinCompatSupportable;

/**
 *
 * 主页
 *
 */
public class MainActivity extends BaseMVVMActivity<MainLayoutBinding,MainViewModel> implements SkinCompatSupportable {
    private static final String TAG = MainActivity.class.getSimpleName();
    private List<Fragment> mFragments;
    private UpgradeManager manager;
    private static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 0x8052;
    private List<NormalItemView> normalItemViewList = new ArrayList<>();
    private AlertDialog dialog;
    NavigationController navigationController;
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.main_layout;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public MainViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MainViewModel.class);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.pSwitchEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {
                if (aBoolean.equals("")){
                    if (dialog!=null){
                        dialog.dismiss();
                    }
                }else {
                    if (dialog!=null){
                        dialog.dismiss();
                    }
                    showUserPhotoDialog(aBoolean);
                }

               //  NimUIKit.startP2PSession(getActivity(),aBoolean);

            }
        });




        viewModel.uc.showJIechu.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {
                if (aBoolean.equals("")){
                    if (dialog!=null){
                        dialog.dismiss();
                    }
                }else {
                    if (dialog!=null){
                        dialog.dismiss();
                    }
                    showUserPhotoDialog(aBoolean);
                }

                //  NimUIKit.startP2PSession(getActivity(),aBoolean);

            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        int uiModel = this.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
        ImmersionBar.with(MainActivity.this). keyboardEnable(false).statusBarDarkFont(uiModel == Configuration.UI_MODE_NIGHT_YES?false:true).init();
        initFragment();
        initBottomTab();
        initServices();
        initLoadData();
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        if (!rid.isEmpty()) {
            JPushInterface.setAlias(getApplicationContext(),0, SPUtils.getInstance().getString(Config.UID));
        } else {
            //Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show();
        }

        onNewIntent(getIntent());


    }

    /**
     * 判断是否可以使用华为推送
     *
     * @return
     */
    public static Boolean canHuaWeiPush() {

        int emuiApiLevel = 0;
        try {
            Class cls = Class.forName("android.os.SystemProperties");
            Method method = cls.getDeclaredMethod("get", new Class[]{String.class});
            emuiApiLevel = Integer.parseInt((String) method.invoke(cls, new Object[]{"ro.build.hw_emui_api_level"}));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return emuiApiLevel > 5.0;

    }


    private void initFragment() {
        mFragments = new ArrayList<>();
        mFragments.add(new MsgHomeFragment());
        mFragments.add(new DiscoverHomeFragment());
        mFragments.add(new MeFragment());
        //默认选中第一个
        commitAllowingStateLoss(0);
    }

    private void initBottomTab() {

        ImmersionBar.with(this).init();



         navigationController = binding.tab.custom()
                .addItem(newItem(R.mipmap.icon_tab_msg_default,R.mipmap.icon_tab_msg_select,"消息"))
                .addItem(newItem(R.mipmap.icon_tab_disvoerdefault,R.mipmap.icon_tab_disvoer_select,"发现"))
                .addItem(newItem(R.mipmap.icon_tab_user_default,R.mipmap.icon_tab_user_select,"我的"))
            //    .addItem(R.mipmap.ic_launcher, "我的")
           //     .setDefaultColor(ContextCompat.getColor(this, R.color.textColorVice))
                .build();
       // navigationController.setHasMessage(0,true);
       // navigationController.setMessageNumber(0,100);
        //navigationController.setMessageNumber(2,2);
        //navigationController.setHasMessage(1,true);
        //底部按钮的点击事件监听

        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
//                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//                transaction.replace(R.id.frameLayout, mFragments.get(index));
//                transaction.commitAllowingStateLoss();
                commitAllowingStateLoss(index);
                int uiModel = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
                switch (index){
                    case 0:

                    ImmersionBar.with(MainActivity.this). keyboardEnable(false).statusBarDarkFont(uiModel == Configuration.UI_MODE_NIGHT_YES?false:true).init();
                    break;
                    case 1:
                        ImmersionBar.with(MainActivity.this). keyboardEnable(false).statusBarDarkFont(uiModel == Configuration.UI_MODE_NIGHT_YES?false:true).init();
                        break;
                    case 2:
                        ImmersionBar.with(MainActivity.this). keyboardEnable(false).statusBarDarkFont(uiModel == Configuration.UI_MODE_NIGHT_YES?false:true).init();
                        break;
                    case 3:
                        ImmersionBar.with(MainActivity.this).keyboardEnable(true).statusBarDarkFont(false).init();
                        break;
                    case 4:
                        ImmersionBar.with(MainActivity.this).keyboardEnable(true).statusBarDarkFont(false).init();

                }
            }

            @Override
            public void onRepeat(int index) {
            }
        });
      //  navigationController.setSelect(1);
        navigationController.setSelect(1);

    }
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text){


        int defaule = SkinCompatResources.getInstance().getColor(this,R.color.bombar_title_defaul);
        int check = SkinCompatResources.getInstance().getColor(this,R.color.bombar_title_select);

        NormalItemView normalItemView = new NormalItemView(this);
        normalItemView.initialize(drawable,checkedDrawable,text);
        normalItemView.setTextDefaultColor(Color.parseColor("#"+Integer.toHexString(defaule)));
        normalItemView.setTextCheckedColor(Color.parseColor("#"+Integer.toHexString(check)));
        normalItemViewList.add(normalItemView);
        return normalItemView;
    }

    private void commitAllowingStateLoss(int position) {
        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragments.get(position);
            transaction.add(R.id.frameLayout, currentFragment, position + "");
        }
        transaction.commitAllowingStateLoss();
    }

    //隐藏所有Fragment
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    public void initServices(){
        checkUpdata();
        viewModel.checkUserVlate();

        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeRecentContact(messageObserver, true);

    }

    public  void initLoadData(){

        viewModel.getUserInfoDetail();
    }

    public void checkUpdata(){
        manager = new UpgradeManager(this);



        manager.checkForUpdates(new UpgradeOptions.Builder()
                .setIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round))
                .setTitle("玩多多")
                .setDescription("下载更新")
                .setUrl(Config.APP_UPDATE)
                .setStorage(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/com.upgrade.apk"))
                .setMultithreadEnabled(true)
                .setMultithreadPools(1)
                .setMd5(null)
                .setAutocleanEnabled(true)
                .setAutomountEnabled(true)
                .build(), new OnUpgradeListener() {

            @Override
            public void onUpdateAvailable(UpgradeClient client) {
            }

            @Override
            public void onUpdateAvailable(Upgrade.Stable stable, UpgradeClient client) {
                showUpgradeDialog(stable, client);
            }

            @Override
            public void onUpdateAvailable(Upgrade.Beta beta, UpgradeClient client) {

            }

            @Override
            public void onNoUpdateAvailable(String message) {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });

//        // 手动检测更新
//        manager.checkForUpdates(new UpgradeOptions.Builder()
//                .setIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_round))
//                .setTitle("腾讯QQ")
//                .setDescription("更新通知栏")
//                .setUrl("https://gitee.com/itsnows/android-upgrade/raw/master/doc/app-update.json")
//                .setStorage(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/com.upgrade.apk"))
//                .setMultithreadEnabled(true)
//                .setMultithreadPools(1)
//                .build(), true);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(manager!=null)manager.cancel();
//  注册/注销观察者
        NIMClient.getService(MsgServiceObserve.class).observeRecentContact(messageObserver,true);
    }

    private double mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis()-mExitTime)>2000) {
                RxToast.showToastShort("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            }else{
                finish();
                AppManager.getAppManager().finishActivity();
                AppManager.getAppManager().AppExit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        if (navigationController!=null){
            navigationController.setMessageNumber(0,unreadNum);
        }

    }

    @Override
    public void applySkin() {

//        for(NormalItemView item:normalItemViewList){
//            int defaule = SkinCompatResources.getInstance().getColor(this,R.color.bombar_title_defaul);
//            int check = SkinCompatResources.getInstance().getColor(this,R.color.bombar_title_select);
//            item.setTextDefaultColor(Color.parseColor("#"+Integer.toHexString(defaule)));
//            item.setTextCheckedColor(Color.parseColor("#"+Integer.toHexString(check)));
//        }
//        Log.d("HTML"," AAAAAAAAAAAAAAAAAA");
//        Messenger.getDefault().sendNoMsg("appcolor");

    }


    public void showUserPhotoDialog(String url){
        View view = View.inflate(this, R.layout.app_checkuser_photo_dialog_custom, null);
        ImageView imgUser = view.findViewById(R.id.img_user);

        GlideUtils.loadImageView(this,url,imgUser);
        final Button btnUpgrade = view.findViewById(R.id.btn_dialog_custom_upgrade);
        dialog = new AlertDialog.Builder(this)
                .setView(view)
                .create();
        dialog.setCancelable(false);
        btnUpgrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPhoto();
            }
        });
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener(){
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                return true;
            }

        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
             //   client.remove();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
               // client.remove();
            }
        });
        dialog.show();

    }
    /**
     * 显示更新提示（自定义提示）
     *
     * @param stable Upgrade.Stable
     * @param client UpgradeClient
     */
    private void showUpgradeDialog(Upgrade.Stable stable, final UpgradeClient client) {
        StringBuffer logs = new StringBuffer();
        for (int i = 0; i < stable.getLogs().size(); i++) {
            logs.append(stable.getLogs().get(i));
            logs.append(i < stable.getLogs().size() - 1 ? "\n" : "");
        }

        View view = View.inflate(this, R.layout.app_update_dialog_custom, null);
        TextView tvMessage = view.findViewById(R.id.tv_dialog_custom_message);
        final Button btnUpgrade = view.findViewById(R.id.btn_dialog_custom_upgrade);
        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(view)
                .create();
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                client.remove();
            }
        });

        tvMessage.setText(logs.toString());
        btnUpgrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 开始下载
                if (mayRequestExternalStorage(MainActivity.this, true)) {
                    client.start();
                }
                dialog.dismiss();
            }
        });
        client.setOnDownloadListener(new OnDownloadListener() {

            @Override
            public void onStart() {
                super.onStart();
                Log.d(TAG, "onStart");
            }

            @Override
            public void onProgress(long max, long progress) {
                Log.d(TAG, "onProgress：" + UpgradeUtil.formatByte(progress) + "/" + UpgradeUtil.formatByte(max));
            }

            @Override
            public void onPause() {
                super.onPause();
                Log.d(TAG, "onPause");
            }

            @Override
            public void onCancel() {
                super.onCancel();
                Log.d(TAG, "onCancel");
            }

            @Override
            public void onError(UpgradeException e) {
                Log.d(TAG, "onError");
            }

            @Override
            public void onComplete() {
                btnUpgrade.setTag(UpgradeConstant.MSG_KEY_DOWNLOAD_COMPLETE_REQ);
                Log.d(TAG, "onComplete");
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                client.remove();
            }
        });
        dialog.show();
    }


    /**
     * 判断申请外部存储所需权限
     *
     * @param context
     * @param isActivate
     * @return
     */
    public boolean mayRequestExternalStorage(Context context, boolean isActivate) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (isActivate) {
            ActivityCompat.requestPermissions((Activity) context,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
        }
        return false;
    }




    public void showPhoto(){
//        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.BLACK)
                // 返回图标ResId
                .backResId(R.mipmap.icon_back)
                // 标题
                .title("图片")
                // 标题文字颜色
                .titleColor(Color.BLACK)
                // TitleBar背景色
                .titleBgColor(Color.WHITE)
                // 裁剪大小。needCrop为true的时候配置
                .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机，默认true
                .needCamera(false)
                // 最大选择图片数量，默认9
                .maxNum(1)
                .build();

// 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, 1);

    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片选择结果回调
        if (requestCode ==  1  && data != null) {
            List<String> pathList = data.getStringArrayListExtra("result");

            Bundle bd = new Bundle();
            bd.putString("img",pathList.get(0));
            bd.putInt("from",0);
            bd.putInt("type",2);
            startContainerActivity(PhotoUploadFragment.class.getCanonicalName(),bd);
           // viewModel.uploadImage(pathList.get(0));

        }
    }

    com.netease.nimlib.sdk.Observer<List<RecentContact>> messageObserver = new com.netease.nimlib.sdk.Observer<List<RecentContact>>() {

        @Override
        public void onEvent(List<RecentContact> recentContacts) {
            int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
            if (navigationController!=null){
                navigationController.setMessageNumber(0,unreadNum);
            }
        }
    };


    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)){
            KLog.d("onNewIntent EXTRA_NOTIFY_CONTENT "+intent.toString());

            ArrayList<IMMessage> list = (ArrayList<IMMessage>) intent.getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            if (list.size()!=0){
//                list.get(0).getSessionId();
                NimUIKit.startP2PSession(this,list.get(0).getSessionId());
            }

        }
        else if (intent.hasExtra("data")){
            String datat = intent.getStringExtra("data");
            try {
                JSONObject jb  = new JSONObject(datat);
               int  type= jb.getInt("Type");
               switch (type){
                   case 1:
                       startContainerActivity(UserInvitationFragment.class.getCanonicalName());
                       break;
                   case 2:
                       startContainerActivity(UserPairFragment.class.getCanonicalName());
                       break;
               }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        KLog.d("onNewIntent"+intent.toString());
    }



}
